package cz.proks.bank.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cz.proks.bank.manager.exeception.UnsupportedCurrencyException;
import cz.proks.bank.service.exchangeratesservice.ExchangeRatesService;
import cz.proks.bank.service.exchangeratesservice.UnsupportedCurrencyFaultException;

@Service
public class CurrencyManager {
	
	@Autowired
	private ExchangeRatesService exchangeRatesClient;
	
	public long convert(long amount, String sourceCurrency, String targetCurrency) throws UnsupportedCurrencyException {
		if (sourceCurrency == null || targetCurrency == null)
			throw new UnsupportedCurrencyException("Source and target currencies cannot be null! Source currency is " + sourceCurrency + ", target currency is " + targetCurrency);
		
		if (sourceCurrency.equals(targetCurrency))
			return amount;
		
		try {
			double ratio = exchangeRatesClient.getExchangeRate(sourceCurrency, targetCurrency).doubleValue();
			return Math.round(amount * ratio);
		} catch (UnsupportedCurrencyFaultException e) {
			throw new UnsupportedCurrencyException("Amount cannot be converted from " + sourceCurrency + " to " + targetCurrency + "!", e);
		}
	}
	
	public boolean isCurrencySupported(String currency) {
		if (currency == null)
			return false;
		
		return exchangeRatesClient.getSupportedCurrencies().contains(currency);
	}
}
